<template>
  <div>
    <a-modal
      :maskClosable="false"
      :title="title"
      centered
      :width="1000"
      v-model="visible"
      :confirmLoading="confirmLoading"
      :bodyStyle="{ padding: 0 }"
      @ok="handleSubmit()"
      :okButtonProps="{
        props: {
          disabled: disabled
        }
      }"
    >
      <a-form-model
        ref="ruleForm"
        class="_pt-10 _pr-20"
        :model="form"
        :rules="rules"
        :labelCol="{ span: 6 }"
        :wrapperCol="{ span: 18 }"
      >
        <a-form-model-item label="头像上传" :labelCol="{ span: 3 }">
          <UploadImg
            v-model="form.avatar"
            :openEditCropper="true"
            cropper
            :width="100"
            :height="125"
            :cropperEnlarge="4"
            :disabled="disabled"
          />
        </a-form-model-item>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="姓名" prop="name">
              <a-input placeholder="请输入姓名" v-model="form.name" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="性别" prop="sex">
              <a-radio-group v-model="form.sex" :disabled="disabled">
                <a-radio value="0">
                  男
                </a-radio>
                <a-radio value="1">
                  女
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="手机号" prop="phone">
              <a-input placeholder="请输入手机号" v-model="form.phone" :disabled="!!form.id || disabled" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="生日" prop="birthday">
              <a-date-picker v-model="form.birthday" valueFormat="YYYY-MM-DD" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="18">
            <a-form-model-item label="籍贯" prop="" :labelCol="{ span: 4 }">
              <div class="_pt-4">
                <AreaPicker childRequired ref="AreaPicker" :area="area" @getArea="getArea" :disabled="disabled" />
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="毕业院校" prop="schoolName">
              <!-- <a-input placeholder="请输入毕业院校1" v-model="form.schoolName" /> -->
              <InputSearch
                :isInternalInterface="InterfaceTypeEnum.School"
                :value="form.schoolName"
                :disabled="disabled"
                placeholder="请输入关键字搜索学校"
                @change="handleChangeSchoolName"
              ></InputSearch>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="邮箱" prop="email">
              <a-input placeholder="请输入邮箱" v-model="form.email" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="微信号" prop="wechatId">
              <a-input placeholder="请输入微信号" v-model="form.wechatId" :disabled="disabled" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="可提供资源" prop="resource">
              <a-textarea
                placeholder="填写可提供资源"
                v-model="form.resource"
                :allowClear="true"
                :maxLength="200"
                :disabled="disabled"
                :auto-size="{ minRows: 5, maxRows: 10 }"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="需求资源" prop="demand">
              <a-textarea
                placeholder="填写需求资源"
                v-model="form.demand"
                :disabled="disabled"
                :maxLength="200"
                :allowClear="true"
                :auto-size="{ minRows: 5, maxRows: 10 }"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <a-card title="单位信息" :bordered="false">
        <template slot="extra" style="padding: 0px">
          <a-button type="primary" @click="openEditCom()" :disabled="disabled">添加单位</a-button>
        </template>
        <div class="disFlxAC" style="flex-wrap: wrap;">
          <div
            v-for="(item, index) in companieList"
            :key="index"
            :class="{ '_pr-5': index % 2 === 0, '_pl-5': index % 2 !== 0, '_pt-10': index > 1 }"
            style="width:50%;flex-shrink: 0;position: relative;"
          >
            <a-card size="small" class="br-5" :headStyle="{ background: '#e5e5e5' }" :bodyStyle="{ padding: '10px' }">
              <template slot="title">
                <span :style="item.authentication ? 'color: #F50;' : ''">{{
                  item.authentication ? '已认证' : '未认证'
                }}</span>
              </template>
              <template slot="extra">
                <!-- 已认证以及默认身份单位不允许删除 -->
                <a-popconfirm
                  v-if="!item.authentication && item.defaultData !== 1"
                  placement="top"
                  title="是否确认删除该单位"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="removeCompany(item, index)"
                >
                  <span v-if="!disabled" style="color: #108ee9;cursor: pointer;" @click="">删除</span>
                </a-popconfirm>
                <span
                  v-if="!item.authentication && !disabled"
                  style="color: #108ee9;cursor: pointer;"
                  class="_pl-10"
                  @click="openEditCom(item)"
                  >修改</span
                >
              </template>
              <div class="disFlxAC" style="min-height: 39px;">
                <a-avatar :size="32" :src="item.logo" icon="bank" style="flex-shrink: 0;" />
                <div class="_pl-10">
                  <div style="color:#333;" class="ov-1">{{ item.name }}</div>
                  <div class="fz-12">{{ item.position }}</div>
                </div>
              </div>
            </a-card>
            <div v-if="item.defaultData === 1" class="defaultID" :class="{ right_5px: index % 2 === 0 }">默认身份</div>
            <div
              v-else-if="showSettingCard(item)"
              class="defaultID setting"
              :class="{ right_5px: index % 2 === 0 }"
              @click="setDefaultIdentityFn(item)"
            >
              设为默认身份
            </div>
          </div>
        </div>
        <a-empty v-if="!companieList.length" description="暂无单位信息" />
      </a-card>
    </a-modal>
    <Editcompany ref="Editcompany" @refresh="getCompanyList" />
  </div>
</template>

<script>
import AreaPicker from '@/components/AreaPicker'
import Editcompany from './editcompany'
import { editUserInfo, getUserCompanies, deleteUserCompanies, setDefaultIdentity } from '@/api/member/user'
import { cloneDeep } from 'lodash-es'
import UploadImg from '@/components/UpFile/uploadImg'
import InputSearch from '@/components/InputSearch'
import { InterfaceTypeEnum } from '@/enums/isInternalInterface'

export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    }
  },
  components: {
    AreaPicker,
    Editcompany,
    UploadImg,
    InputSearch
  },
  computed: {
    area: function() {
      return this.form.nativePlace && this.form.nativePlace.length
        ? { provinceId: this.form.nativePlace[0], cityId: this.form.nativePlace[1], areaId: this.form.nativePlace[2] }
        : {}
    }
  },
  data() {
    return {
      InterfaceTypeEnum,
      title: '新增用户',
      visible: false,
      confirmLoading: false,
      form: {
        id: undefined,
        avatar: '', // 头像
        name: '', // 姓名
        sex: '0', // 性别
        phone: '', // 手机号
        birthday: '', // 生日
        nativePlace: [], // 籍贯
        schoolName: '', // 毕业院校
        email: '', // 邮箱
        wechatId: '', // 微信号
        companyId: undefined, // 默认单位ID
        demand: '', // 需求资源
        resource: '' // 提供资源
      },
      companieList: [], // 所有单位列表

      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 2, max: 8, message: '姓名长度不符,最少2位最多8位', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1\d{10}$/, message: '手机号格式错误', trigger: 'blur' }
        ],
        email: [
          {
            pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            message: '邮箱格式错误',
            trigger: 'blur'
          }
        ],
        wechatId: [{ pattern: /^[a-zA-Z][-_a-zA-Z0-9]{5,19}$/, message: '微信号格式错误', trigger: 'blur' }]
      }
    }
  },
  methods: {
    show(row) {
      Object.assign(this.$data.form, this.$options.data().form) // 重置数据
      this.companieList = []
      this.visible = true
      this.title = row ? '个人信息' : '新增用户'
      if (row) {
        for (const key in this.form) {
          if (key === 'nativePlace') {
            if (row[key]) {
              this.form[key] = row[key].split(',')
              this.form[key].forEach((v, i) => {
                this.form[key][i] = parseInt(v)
              })
            } else {
              this.form[key] = []
            }
          } else {
            this.form[key] = row[key]
          }
        }
        this.getCompanyList() // 获取单位列表
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()
      })
    },
    getArea(val) {
      this.form.nativePlace = []
      Object.entries(val).forEach(([key, value]) => {
        if (value) {
          this.form.nativePlace.push(value)
        }
      })
    },
    // 初始化单位列表
    async getCompanyList() {
      const { data } = await getUserCompanies({ appUserInfoId: this.form.id })

      // 根据默认单位ID匹配默认单位
      // 匹配规则, 优先匹配已认证, 其次是未认证
      // ID匹配不到则默认设置, 优先设置已认证第一个,其次设置未认证第一个
      let attestationCompanieList = data.filter(v => v.authentication === true) // 已认证单位
      let companyInfoDtoList = data.filter(v => v.authentication === false) // 未认证单位
      let defaultCompanie = undefined

      attestationCompanieList.forEach((v, i) => {
        if (v.id === this.form.companyId && !defaultCompanie) {
          this.$set(v, 'defaultData', 1) //   1 默认 0 非默认
          defaultCompanie = v
        } else {
          this.$set(v, 'defaultData', 0)
        }
      })
      companyInfoDtoList.forEach((v, i) => {
        if (v.id === this.form.companyId && !defaultCompanie) {
          this.$set(v, 'defaultData', 1) //   1 默认 0 非默认
          defaultCompanie = v
        } else {
          this.$set(v, 'defaultData', 0)
        }
      })

      // 都未匹配到,赋值默认值 - 优先赋值已认证
      if (!defaultCompanie && attestationCompanieList.length) {
        attestationCompanieList[0].defaultData = 1
        defaultCompanie = attestationCompanieList[0]
        this.setDefaultIdentityFn(defaultCompanie) // 设置默认单位
      }
      if (!defaultCompanie && companyInfoDtoList.length) {
        companyInfoDtoList[0].defaultData = 1
        defaultCompanie = companyInfoDtoList[0]
        this.setDefaultIdentityFn(defaultCompanie) // 设置默认单位
      }

      this.companieList = [...attestationCompanieList, ...companyInfoDtoList]
    },
    // 删除单位-只能删除未认证单位
    removeCompany(company, index) {
      deleteUserCompanies(company.id).then(() => {
        this.$message.success('单位删除成功')
        this.getCompanyList()
      })
    },
    // 设置默认单位
    setDefaultIdentityFn(company) {
      setDefaultIdentity({
        appUserInfoId: this.form.id,
        companyName: company.name,
        companyId: company.id,
        companyPositionName: company.position
      }).then(() => {
        this.form.companyId = company.id
        this.getCompanyList()
      })
    },
    // 打开新增单位弹窗, 必须先新增用户
    openEditCom(company) {
      if (!this.form.id) {
        this.handleSubmit(true)
      } else {
        this.$refs.Editcompany.show(this.form.id, company)
      }
    },
    // 新增用户 || 编辑用户
    handleSubmit(isAddCompanie) {
      const _that = this
      console.log(JSON.parse(JSON.stringify(_that.form)))
      _that.$refs.ruleForm.validate(valid => {
        if (valid) {
          let params = cloneDeep(_that.form)
          params.nativePlace = params.nativePlace.join(',')
          if (isAddCompanie) {
            // 点击新增单位,且没有用户ID时
            _that.$confirm({
              title: '确认新增用户?',
              content: '添加单位之前,必须要先新增用户,是否确认新增用户?',
              centered: true,
              onOk() {
                return new Promise((resolve, reject) => {
                  editUserInfo(params)
                    .then(res => {
                      _that.$emit('refresh')
                      _that.$message.success('新增成功')
                      _that.form.id = res.data.id
                      _that.openEditCom()
                      resolve(res)
                    })
                    .catch(err => {
                      reject(err)
                    })
                })
              }
            })
          } else {
            editUserInfo(params).then(() => {
              _that.$emit('refresh')
              _that.visible = false
              _that.$message.success(params.id ? '修改成功' : '新增成功')
            })
          }
        } else {
          _that.$message.error('请先填写用户信息')
        }
      })
    },
    // 是否显示 设置默认身份
    showSettingCard(item) {
      let attestationCompanieList = this.companieList.filter(v => v.authentication === true) // 已认证单位
      if (attestationCompanieList.length && !item.authentication) {
        // 存在已认证单位,且当前是未认证单位,不能设置默认身份
        return false
      }
      return true
    },
    handleChangeSchoolName({ value }) {
      this.form.schoolName = value
    }
  }
}
</script>

<style lang="less" scoped>
.defaultID {
  position: absolute;
  font-size: 12px;
  bottom: 0;
  right: 0;
  background-color: red;
  color: #fff;
  padding: 0 10px;
  border-radius: 5px 0 5px 0;
}
.defaultID.right_5px {
  right: 5px;
}
.defaultID.setting {
  background-color: #fff;
  color: #87d068;
  border: solid 1px #e8e8e8;
  cursor: pointer;
}
</style>
